import router from "@/router";
import store from "@/store";
import checkAccess from "@/access/checkAccess";
import accessEnum from "@/access/accessEnum";

router.beforeEach(async (to, from, next) => {
  let loginUser = store.state.user.loginUser;
  // 如果用户未登录
  if (
    !loginUser ||
    !loginUser.userRole ||
    loginUser.userRole === accessEnum.NOT_LOGIN
  ) {
    await store.dispatch("user/getLoginUser");
    loginUser = store.state.user.loginUser;
  }
  const needAccess = (to.meta?.access as string) ?? accessEnum.NOT_LOGIN;
  // 如果网页需要登录
  if (needAccess !== accessEnum.NOT_LOGIN) {
    // 但是用户未登录
    if (!loginUser || !loginUser.userRole) {
      next("/user/login");
      return;
    }
    // 或者用户权限不够
    if (!checkAccess(loginUser, needAccess)) {
      next("/noAuth");
      return;
    }
  }
  next();
});
